package com.zzl.alligator.common.constant;

import com.zzl.alligator.common.util.ServletUtils;
import com.zzl.alligator.common.util.SpringUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 项目信息
 *
 * @author zhouziliang
 * @since 2020/6/27
 */
@Component
@ConfigurationProperties(prefix = "alligator")
@Data
public class ProjectProperties {

    /**
     * 项目名称
     */
    private String name;

    /**
     * 版本
     */
    private String version;

    /**
     * 版权年份
     */
    private String copyrightYear;

    /**
     * 实例演示开关
     */
    private boolean demoEnabled;

    /**
     * 上传路径
     */
    private String profile;

    /**
     * 获取地址开关
     */
    private boolean addressEnabled;

    /**
     * 是否允许修改admin密码
     */
    private boolean allowChangeAdminPassword;

    /**
     * 获取头像上传路径
     */
    public String getAvatarPath() {
        return this.profile + "/avatar";
    }

    /**
     * 获取下载路径
     */
    public String getDownloadPath() {
        return this.profile + "/download/";
    }

    public static ProjectProperties getInstance() {
        return SpringUtils.getBean(ProjectProperties.class);
    }

    /**
     * 获取上传路径
     */
    public String getUploadPath() {
        return this.profile + "/upload";
    }

    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     *
     * @return 服务地址
     */
    public String getUrl() {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    public static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }
}
